package org.csu.mypetstore.web.servlets;

import org.apache.commons.beanutils.BeanUtils;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.service.AccountService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/updatemyaccount")
public class UpdateMyAccountServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Map<String, String[]> map = req.getParameterMap();
        if ((req.getParameter("password")!=null)&&(!req.getParameter("repeatedPassword").equals(req.getParameter("password")))){
            System.out.println("两次密码输入不一致，请重新输入");
            req.setAttribute("update_msg","两次密码输入不一致，请重新输入");
            req.getRequestDispatcher("/WEB-INF/jsp/account/EditAccountForm.jsp").forward(req,resp);
            return;
        }
        AccountService service = new AccountService();
        Account account = new Account();
        Account account1 =(Account) req.getSession().getAttribute("account");//带密码的
        String username = account1.getUsername();
        String password = account1.getPassword();
        account.setUsername(account1.getUsername());
        try {
            BeanUtils.populate(account,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        service.updateAccount(account);
        req.getSession().setAttribute("account",account);
        resp.sendRedirect(req.getContextPath()+"/showmyaccount");

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
